var fm_listingTable;
var fm_sentTime;
var fm_pendingListings = 0;
// Fm
var fm_content;
var fm_tab;
var fm_popupOverwrite;
var fm_popupNoSlicing;
var fm_popupFileSelect;
var fm_list;
var fm_legend;
var fm_bThrash;
var fm_bUp;
var fm_bInvert;
var fm_bNew;
var fm_currentList;
var fm_requiredPath;
var ic_folder = new Image();
ic_folder.src = "folder.png";
var ic_file = new Image();
ic_file.src = "file.png";
var selectedColor = "#009900";
var fm_newFolderInput;

/*
 * File manager functions
 */

function fm_init() {
	fm_content = document.getElementById("fm_content");
	fm_tab = main_createTab("fm_content", _T("Files"));
	main_contents.push(fm_content);
	// Tools
	fm_bThrash = main_createTool(_T("Delete"), "fm_deleteSelected();");
	fm_bUp = main_createTool(_T("Upload"),
			"popup_show('"+_T("SelectFilesToUpload")+"',fm_popupFileSelect,'fm_fileselect')");
	fm_bNew = main_createTool(_T("NewFolder"), "fm_newFolder()");
	fm_bInvert = main_createTool(_T("Invert"), "fm_invertSelection();");
	// Popup - overwrite
	fm_popupOverwrite = document.createElement("p");
	var head = document.createElement("p");
	head.appendChild(document.createTextNode(_T("FM_OverHead")));
	fm_popupOverwrite.appendChild(head);
	fm_popupOverwrite.appendChild(fm_createButton(_T("Replace"),
			"fm_uploader.startReplace();", _T("FM_Replace")));
	fm_popupOverwrite.appendChild(fm_createButton(_T("Append"),
			"fm_uploader.startAppend();", _T("FM_Append")));
	fm_popupOverwrite.appendChild(fm_createButton(_T("Skip"),
			"fm_uploader.startSkip();", _T("FM_Skip")));
	// Popup - no slicing
	fm_popupNoSlicing = document.createElement("p");
	var head = document.createElement("p");
	head.appendChild(document.createTextNode(_T("FM_NoSlicing")));
	fm_popupNoSlicing.appendChild(head);
	fm_popupNoSlicing.appendChild(main_createButton(_T("Yes"),
			"fm_uploader.uploadFile();"));
	fm_popupNoSlicing.appendChild(main_createButton(_T("No"),
	"popup_hide('fm_noSlicingPopup');"));
	// Popup - select files
	fm_popupFileSelect = document.createElement("p");
	var input = document.createElement("input");
	input.type = "file";
	input.multiple = "true";
	input
			.setAttribute("onChange",
					"popup_hide('fm_fileselect');fm_uploadFiles(fm_currentList.file.path,this)");
	fm_popupFileSelect.appendChild(input);
	// Legned and list
	fm_legend = document.createElement("div");
	fm_list = document.createElement("div");
	fm_content.appendChild(fm_legend);
	fm_content.appendChild(fm_list);
}

function fm_createButton(_title, _onClick, _desc) {
	var p = document.createElement("p");
	var button = main_createButton(_title, _onClick);
	p.appendChild(button);
	p.appendChild(document.createTextNode(_desc));
	return p;
}

function fm_onShow() {
	main_toolbar.appendChild(fm_bThrash);
	main_toolbar.appendChild(fm_bUp);
	main_toolbar.appendChild(fm_bNew);
	main_toolbar.appendChild(fm_bInvert);
}

function fm_updateFm() {
	fm_ls(fm_requiredPath);
}
function fm_ls(_path) {
	fm_requiredPath = _path;
	fm_innerLs(fm_requiredPath);
	return false;
}

function fm_innerLs(_path) {
	fm_pendingListings++;
	var req = new XMLHttpRequest();
	req.onreadystatechange = function() {
		if (req.readyState == 4 && req.status == 200) {
			addPing(new Date().getTime() - fm_sentTime);
			fm_pendingListings--;
			if (fm_pendingListings == 0) {
				fm_currentList = main_readJSONResponse(req);
				if(!fm_currentList){
					return;
				}
				if (fm_currentList.file.path == fm_requiredPath) {
					fm_fillFm();
				}
			}
		}
	};
	main_encryptReq(req,"fm",_path);
	fm_sentTime = new Date().getTime();
}

function fm_toggleSelection(_item) {
	var path = _item.id;
	path = path.substring(2);
	row = document.getElementById(path);
	if (fm_currentList.ls[path].selected) {
		fm_currentList.ls[path].selected = false;
		row.style.background = "";
	} else {
		fm_currentList.ls[path].selected = true;
		row.style.background = selectedColor;
	}
	fm_updateToolbar();
}

/*
 * Invert the selection
 */
function fm_invertSelection() {
	for (item in fm_currentList.ls) {
		fm_currentList.ls[item].selected = !fm_currentList.ls[item].selected;
		var element = document.getElementById(item);
		if (fm_currentList.ls[item].selected) {
			element.style.background = selectedColor;
		} else {
			element.style.background = "";
		}
	}
	fm_updateToolbar();
}
/*
 * Create a new folder
 */
function fm_newFolder() {
	var content = document.createElement("div");
	var message = document.createElement("div");
	message.textContent = _T("EnterTheFoldersName");
	content.appendChild(message);
	fm_newFolderInput = document.createElement("input");
	fm_newFolderInput.value = _T("NewFolder");
	content.appendChild(fm_newFolderInput);
	popup_showDialog(_T("Confirm"), content, "fm_confirmedNewFolder()", "");
}

function fm_confirmedNewFolder() {
	var name = fm_newFolderInput.value;
	if (name == null || name.length < 1) {
		return;
	}
	var dir = fm_currentList.file.path;
	if (dir == "/") {
		dir = "";
	}
	var path = dir + "/" + name;
	for (item in fm_currentList.ls) {
		if (fm_currentList.ls[item].path == path) {
			alert(path + ": "+ _T("AlreadyExists"));
			return;
		}
	}
	var req = new XMLHttpRequest();
	req.onreadystatechange = function() {
		if (req.readyState == 4 && req.status == 200) {
			var report=main_readJSONResponse(req);
			if(!report){
				return;
			}
			var path = report.file.path;
			var index = path.lastIndexOf("/");
			var parent = path.substring(0, index);
			if (parent.length < 1) {
				parent = "/";
			}
			if (fm_requiredPath == parent) {
				fm_innerLs(fm_requiredPath);
			}
		}
	};
	main_encryptReq(x,"fm_mkdir",path);
}

function fm_updateToolbar() {
	count = 0;
	onlyFiles = true;
	onlyDirs = true;
	for (item in fm_currentList.ls) {
		if (fm_currentList.ls[item].selected) {
			count++;
			if (fm_currentList.ls[item].isDir) {
				onlyFiles = false;
			} else {
				onlyDirs = false;
			}
		}
	}
	fm_bInvert.style.display = "inline-block";
	fm_bThrash.style.display = "none";
	fm_bUp.style.display = "none";
	fm_bNew.style.display = "none";
	if (count < 1) {
		fm_bNew.style.display = "inline-block";
	}
	if (count > 0) {
		fm_bThrash.style.display = "inline-block";
	}
	if (count < 2 && onlyDirs) {
		fm_bUp.style.display = "inline-block";
	}
}

function fm_fillFm() {
	var file = fm_currentList.file;
	var list = fm_currentList.ls;
	fm_legend.innerHTML = file.path;
	while (fm_list.firstChild) {
		fm_list.removeChild(fm_list.firstChild);
	}
	fm_listingTable = document.createElement("table");
	if (file.path.length > 1) { // Not the '/'
		fm_fillFile(file, true);
	}
	var sortedPaths = new Array();
	for (path in list) {
		sortedPaths.push(path);
	}
	sortedPaths.sort();
	for ( var i = 0; i < sortedPaths.length; i++) {
		fm_fillFile(list[sortedPaths[i]], false);
	}
	fm_list.appendChild(fm_listingTable);
	fm_updateToolbar();
}

function fm_fillFile(_file, _isParent) {
	var file = new fm_FmFile(_file);
	var fileName = file.name;
	var path = file.path;
	var trClass = "";
	var iconOnclick = "";
	var aOnclick = "";
	var aClass = "";
	var aTarget = "";
	var aHref = "";

	if (_isParent) {
		fileName = " • • ";
		path = file.parent;
	} else {
		iconOnclick = "fm_toggleSelection(this);";
	}
	if (file.isDir) {
		aHref = "#";
		aOnclick = "fm_ls('" + path + "');";
		aClass = "dir";
		aTarget = "_self";
	} else {
		aHref = "fm" + path;
		aClass = "file";
		aTarget = "_blank";
	}
	if (!file.isDir || file.size != _T("Empty")) {
		trClass = "fm";
	} else {
		trClass = "grayed";
	}
	var tr = document.createElement("tr");
	tr.setAttribute("class", trClass);
	tr.setAttribute("id", path);
	var tdIcon = document.createElement("td");
	tdIcon.setAttribute("id", "i_" + path);
	tdIcon.setAttribute("onclick", iconOnclick);
	tdIcon.setAttribute("class", "icon");
	var imgIcon = document.createElement("img");
	imgIcon.setAttribute("src", file.icon);
	tdIcon.appendChild(imgIcon);
	var tdName = document.createElement("td");
	tdName.setAttribute("class", "name");
	var aName = document.createElement("a");
	aName.setAttribute("href", aHref);
	aName.setAttribute("onclick", aOnclick+"return false;");
	aName.setAttribute("target", aTarget);
	aName.setAttribute("class", aClass);
	aName.appendChild(document.createTextNode(fileName));
	tdName.appendChild(aName);
	var tdSize = document.createElement("td");
	tdSize.setAttribute("class", "size");
	tdSize.appendChild(document.createTextNode(file.size));
	tr.appendChild(tdIcon);
	tr.appendChild(tdName);
	tr.appendChild(tdSize);
	fm_listingTable.appendChild(tr);
}

function fm_FmFile(_file) {
	this.index = _file.path.lastIndexOf("/");
	this.path = _file.path;
	this.parent = this.path.substring(0, this.index);
	if (this.parent.length < 1) {
		this.parent = "/";
	}
	this.name = this.path.substring(this.index + 1);
	this.isDir = _file.isDir;
	this.icon = null;
	this.size = "???";
	if (this.isDir) {
		if (_file.size == 0) {
			this.size = _T("Empty");
		} else {
			this.size = _file.size + _T("ItDot");
		}
		this.icon = "folder.png";
	} else {
		this.size = new Size(_file.size).string();
		var suffix = this.name.substring(this.name.lastIndexOf(".") + 1)
				.toLowerCase();
		this.icon = fm_mimes[suffix];
		if (this.icon == null) {
			this.icon = "file.png";
		}
	}
}
